package com.nwpu.am.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.nwpu.am.mapper.PartMapper;
import com.nwpu.am.pojo.dto.PartAddDTO;
import com.nwpu.am.pojo.dto.PartDeleteDTO;
import com.nwpu.am.pojo.dto.PartFindDTO;
import com.nwpu.am.pojo.dto.PartUpdateDTO;
import com.nwpu.am.pojo.entity.Part;
import com.nwpu.am.result.PageResult;
import com.nwpu.am.service.PartService;
import com.nwpu.am.utils.id_generator.IdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * PartServiceImpl
 *
 * @author Du
 * @version 1.0
 * {@code @date} 2024/6/5
 */

@Service
@Slf4j
public class PartServiceImpl implements PartService {
    @Resource
    private PartMapper partMapper;

    @Resource
    private IdGenerator idGenerator;

    @Override
    public PageResult<Part> pageQuery(PartFindDTO partFindDTO) {
        // 开启分页插件
        PageMethod.startPage(partFindDTO.getPage(), partFindDTO.getPageSize());

        // 调用分页方法
        Page<Part> page = partMapper.selectPartByPartFindDTO(partFindDTO);

        long total = page.getTotal();
        List<Part> result = page.getResult();

        return new PageResult<>(total, result);
    }

    @Override
    public ArrayList<Part> findPartByName(String partName) {
        return partMapper.selectPartByName(partName);
    }

    @Override
    public Part findPartById(long partId){
        return partMapper.selectPartById(partId);
    }

    @Override
    public Part findPartByNameId(String partName, long warehouseId){
        return partMapper.selectPartByNameId(partName,warehouseId);
    }


    @Override
    public ArrayList<Part> display() {
        return partMapper.selectAll();
    }

    @Override
    @Transactional
    public Part updatePart(PartUpdateDTO partUpdateDTO) {
        Part part = partMapper.selectPartByNameId(partUpdateDTO.getPartName(),partUpdateDTO.getWarehouseId());
        part.setPartNum(part.getPartNum() + partUpdateDTO.getFluctuation());
        partMapper.updatePart(part);
        return part;
    }

    @Override
    public Part addPart(PartAddDTO partAddDTO) {
        long partId = idGenerator.nextId();
        Part part = new Part(partId, partAddDTO.getPartName(), partAddDTO.getPartNum(),
                partAddDTO.getPrice(), partAddDTO.getWarehouseId());
        partMapper.insertPart(part);
        return part;
    }

    @Override
    public void deletePart(PartDeleteDTO partDeleteDTO) {
        partMapper.deletePartByNameId(partDeleteDTO.getPartName(),partDeleteDTO.getWarehouseId());
    }

}
